<?php 

namespace app\controller\bossManager;

use share\service\RedisService;

class CacheController extends WebBossController{


    public function key_detail_action(){
        $param = $this->request->param();
        $redis = self::getRedisHandle($param);
        $key = $param['key'];
        $ttl = $redis->ttl($key);
        $type = $redis->type($key);
        $val = '';
        if($type == 1){
            $val = $redis->get($key);
        }
        return self::ok([
            'key' => $key,
            'ttl' => $ttl,
            'type' => $type,
            'val' => $val
        ]);
    }

    public function keys_action(){
        $param = $this->request->param();   
        $redis = self::getRedisHandle($param);     
        $res = $redis->keys($param['key']);
        // $res = $redis->scan($cursor,$param['key'], $param['count']);
        $len = count($res);
        if($len >  1000){
            $res = array_slice($res,0,1000);
        }
        return self::ok([
            'size' => $len,
            'keys' => $res,
        ]);
    }

    public function del_action(){
        $param = $this->request->param();   
        $redis = self::getRedisHandle($param);     
        $res = $redis->del($param['key']);
        return self::ok($res);
    }

    public function hget_action(){
        $param = $this->request->param();   
        $redis = self::getRedisHandle($param);
        $res = $redis->hGet($param['key'],$param['field']);
        return self::ok([
            'key' => $param['key'],
            'field' => $param['field'],
            'val' => $res,
        ]);
    }

    public function hdel_action(){
        $param = $this->request->param();   
        $redis = self::getRedisHandle($param);
        $res = $redis->hDel($param['key'],$param['field']);
        return self::ok($res);
    }

    public static function getRedisHandle($param){
        $config = RedisService::getRedisCacheConfig();
        $currentConfig = $config[RedisService::CACHE_DB_BASE];
        $currentConfig['db'] = $param['db'];
        $redis = RedisService::getRedisHandleByConfig($currentConfig);
        return $redis;
    }

}
